﻿#if NETSTANDARD2_0 || NETCOREAPP3_0
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
#else
using System.IO;
#endif
using System;
using System.Collections.Specialized;

namespace Longbow.Logging
{
    /// <summary>
    /// 异常管理操作类
    /// </summary>
    public static class ExceptionManager
    {
#if NETSTANDARD2_0 || NETCOREAPP3_0
        private static IServiceCollection _services;
        private static Lazy<ILogger> _logger = new Lazy<ILogger>(() => _services.BuildServiceProvider().GetRequiredService<ILogger<FileLogger>>());

        /// <summary>
        /// 异常日志注入时调用
        /// </summary>
        /// <param name="services">IServiceCollection 实例</param>
        internal static void RegisterExceptionManager(this IServiceCollection services) => _services = services;

        /// <summary>
        /// 记录日志方法
        /// </summary>
        /// <param name="ex">Exception 实例</param>
        /// <param name="nv">日志附属信息</param>
        public static void Publish(Exception ex, NameValueCollection nv = null) => _logger.Value.Log(LogLevel.Error, 0, nv, ex, (n, e) => string.Empty);
#else
        private static FileLoggerProvider _provider = new FileLoggerProvider(new FileLoggerOptions() { FileName = $"Error{Path.DirectorySeparatorChar}Error.log" });
        private static Lazy<ILogger> _logger = new Lazy<ILogger>(() => _provider.CreateLogger(nameof(ExceptionManager)));

        /// <summary>
        /// 记录日志方法
        /// </summary>
        /// <param name="ex">Exception 实例</param>
        /// <param name="nv">日志附属信息</param>
        public static void Publish(Exception ex, NameValueCollection nv = null) => _logger.Value.Log(LogLevel.Error, ex.FormatException(nv));

        /// <summary>
        /// 强制输出到日志文件
        /// </summary>
        public static void Flush() => _provider.Flush();
#endif
    }
}
